package es.tid.www.wsdl.parlayx.presence.consumer.v1_1.wsconsumer;

import java.util.HashMap;

public class LineStateFlags {

	/**
	 * stores the line states for the queried presentities
	 */
	private HashMap lineStates;
	/**
	 * stores an entry for every correlator and presentity.
	 */
	private HashMap correlators;
	/**
	 * unique instance to be used anywhere needed
	 */
	private static LineStateFlags instance;
	
	/**
	 * inits unique instance
	 */
	private LineStateFlags(){
		lineStates=new HashMap();
		correlators=new HashMap();
	}
	
	/**
	 * gets the unique instance and builds a new one if not done yet
	 * @return unique instance
	 */
	public static LineStateFlags getInstance(){
		if (instance==null){
			instance=new LineStateFlags();
		}
		return instance;
	}
	
	/**
	 * queries the line state for a concrete presentity
	 * @param uri sip address of the presentity to query for its line state
	 * @return true if line state is busy
	 */
	public synchronized boolean getLineState(String uri){
		if (lineStates!=null){
			return ((Boolean)lineStates.get(uri)).booleanValue();
		}
		else{
			return false;
		}
	}
	
	/**
	 * sets value for one presentity line state
	 * @param uri sip address of the presentity to set the line state
	 * @param busyValue true if line state must be changed to busy
	 */
	public synchronized void setLineState(String uri,boolean busyValue){
		lineStates.put(uri, busyValue);
	}
	
	/**
	 * Adds a correlator related to a presentity
	 * @param presentity sipaddress of the presentity linked to the correlator
	 * @return the created correlator linked to the presentity received as param.
	 */
	public synchronized String addCorrelatorFor(String presentity){
		String correlator=generateCorrelator();
		correlators.put(presentity,correlator);
		return correlator;
	}
	
	/**
	 * Obtains the correlator related to a certain presentity
	 * @param presentity sip address of the presentity whose correlator is wanted to know
	 * @return the presentity's related correlator
	 */
	public synchronized String getCorrelator(String presentity){
		return (String)correlators.get(presentity);
	}
	
	/**
	 * generates a new correlator, based in current time and a random number
	 * @return the new correlator value
	 */
	private String generateCorrelator(){
		return new Integer((int)(Math.random() * 10000)).toString() + new Long(System.currentTimeMillis()).toString();
	}
	
}
